<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\MoneyLog;
use app\common\model\option\Log as OptionLog;
use app\common\model\order\Order;
use app\common\model\ScoreLog;
use app\common\model\User as ModelUser;
use app\common\model\user\Address;
use app\common\model\user\Info;
use app\common\model\user\Withdrawal;
use app\common\model\user\Ys;
use fast\Http;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\Log;
use think\Session;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin',  'changemobile', 'wxLogin', 'miniLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = $this->auth->getUser();
        if (!$userInfo->qr_image) {
            ModelUser::where('id', $userInfo->id)->update(['qr_image'   => build(cdnurl('/h5/#/?code=' . $userInfo->code, true))]);
            $userInfo = $this->auth->getUser();
        }
        if ($userInfo->level == 7) {
            $totalMoney = Order::where('status', '>', '0')->where('user_id', $userInfo->id)->sum('pay_money');
            $userInfo['dividendMoney'] = bcmul($totalMoney, 0.02, 2);
        }
        $this->success('', $userInfo);
    }
    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->post("mobile");
        $newpassword = $this->request->post("newpassword");
        $oldpassword = $this->request->post("oldpassword");
        $ignoreoldpassword = $this->request->post("ignoreoldpassword");
        if (!$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:^\d{6}$'])) {
            $this->error(__('请输入6位数字密码'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepaypwd($newpassword, $oldpassword, $ignoreoldpassword);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $post = $this->request->post();
        extract($post);
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha) && $captcha != '888888') {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        $extend = [];
        $token = '';
        if (isset($login_type) && $login_type == 'mini') {
            // 入参
            if (empty($wxcode)) {
                $this->error('缺少必要参数!');
            }
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($wxcode);
            if (!isset($decryptSession['session_key'])) {
                $this->error($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                $this->error('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                $this->error('code错误,请重试!');
            }
            $openid = $decryptSession['openid'];
            $decrypt = $wechat->getAccessToken();
            $token = $extend['token'] = $decrypt['access_token'];
            $extend['login_type'] = $login_type;
        }
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, $token);
        } else {
            $ret = $this->auth->register($nickname ?? '', Random::alnum(), $code ?? '', $mobile, $extend);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo(), 'openid' => $openid ?? ''];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 网页授权获取code
     */
    public function getWxOfficialAccountCode()
    {
        // TODO 前期测试用于清空值 Session::set('wechat_user', NULL);
        if (!Session::has('wechat_user')) {
            $wechat = new Wechat('wxOfficialAccount');
            $oauth = $wechat->oauth();
            return $oauth->redirect()->send();
        } else {
            $this->success('授权登录成功(缓存)', Session::get('wechat_user'));
        }
    }
    /**
     * 微信公众号登录、更新信息、绑定(授权页 非api)
     *
     * @param string $code 加密code
     * @return array
     */
    public function wxOfficialAccountOauth()
    {
        $params = $this->request->get();
        $wechat = new Wechat('wxOfficialAccount');
        $oauth = $wechat->oauth();
        $decryptData = $oauth->user()->getOriginal();
        if (!$decryptData || !isset($decryptData['openid']) || !isset($decryptData['unionid'])) {
            Log::error('未获取到登录状态：' . json_encode($decryptData));
            exception('未获取到登录状态,请重试!');
        }
        if (empty($decryptData['openid']) || empty($decryptData['unionid'])) {
            exception('code错误,请重试!');
        }
        if (isset($decryptData['openid'])) {
            $where['openid'] = ['=', $decryptData['openid']];
        }
        if (isset($decryptData['unionid'])) {
            $where['unionid'] = ['=', $decryptData['unionid']];
        }
        /* $decryptData 输出结果
         * Array (
            [openid] => o5dGW6J0AIQxnM2nM549ukHrYC-8
            [nickname] => 霍文霆
            [sex] => 0
            [language] =>
            [city] =>
            [province] =>
            [country] =>
            [headimgurl] => https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJj3N9WvKoQia9ibbIe6AtdT7vZ8cCpzK53ycnFMCFwsg3fTovotvEzvKbHXm5iaqLayc0ALe1nO1WBw/132
            [privilege] => Array()
            [unionid] => oqN-A6hQFIM-drK14aF8kxt0ajcA
        )*/

        $result = [];
        try {
            $user = \app\common\model\User::get($where);
            if ($user) {
                if ($user->status !== 'normal') {
                    $this->error(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                $decryptData['h5_openid'] = $decryptData['openid'];
                $result = $this->auth->oauthRegister($decryptData, 'wxOfficialAccount');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $wechat_user = $this->auth->getUserInfo();
            // 把用户登录信息写入session中，这样可以减少服务器不必要的开销
            Session::set('wechat_user', $wechat_user);
            $this->success('授权登录成功', $wechat_user);
        } else {
            $this->error('授权登录失败了!');
        }
    }
    /**
     * 微信小程序登录
     *
     * @params string $openid 唯一标识
     * @params string $sessionKey 秘钥
     * @params string $iv 偏移量
     * @params string $encryptedData 加密串
     * @return array
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);

        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            // 分参
            $decrypt = $wechat->getAccessToken();
            $token = $decrypt['access_token'];
            // $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
            // $client = new \GuzzleHttp\Client();
            // $response = $client->post($url, [
            //     'json' => [        //参数组
            //         'code' => $phoneCode
            //     ]
            // ]);
            // $res = $response->getBody();
            // $res = json_decode($res, 1);
            // if ($res['errcode'] == 0) {
            //     $phone = $res['phone_info'];
            // } else {
            //     exception('失败:' . $res['errmsg']);
            // }
            $user = \app\common\model\User::get([
                'mini_openid'   => $decryptSession['openid']
            ]);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                if (isset($pid) && !empty($pid)) {
                    $decryptSession['pid'] = $pid;
                }
                $decryptSession['mini_openid'] = $decryptSession['openid'];
                $decryptSession['token'] = $token;

                unset($decryptSession['openid']);
                // $decryptSession['phoneNumber'] = $phone['phoneNumber'];
                // $decryptSession['token'] = $phone['token'];
                // 写入个人数据
                //  if (isset($share_code) && !empty($share_code)) {
                //     $p_user = \app\common\model\User::get(['code' => $share_code]);
                //     if (isset($p_user) && !empty($p_user)) {
                //         $decryptData['pid'] = $p_user['id'];
                //     }
                // }
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 微信登录
     *
     * @params string $openid 唯一标识
     * @params string $sessionKey 秘钥
     * @params string $iv 偏移量
     * @params string $encryptedData 加密串
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxAppProgram');
            $decryptData = $wechat->wxAppLogin($code);

            Log::error('登录数据：' . json_encode($decryptData));

            if (!$decryptData || !isset($decryptData['openid']) || !isset($decryptData['unionid'])) {
                Log::error('未获取到登录状态：' . json_encode($decryptData));
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptData['openid']) || empty($decryptData['unionid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptData['openid'])) {
                $where['openid'] = ['=', $decryptData['openid']];
            }
            if (isset($decryptData['unionid'])) {
                $where['unionid'] = ['=', $decryptData['unionid']];
            }
            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                if (isset($share_code) && !empty($share_code)) {
                    $p_user = \app\common\model\User::get(['code' => $share_code]);
                    if (isset($p_user) && !empty($p_user)) {
                        $decryptData['pid'] = $p_user['id'];
                    }
                }
                $result = $this->auth->oauthRegister($decryptData);
            }
        } catch (\Exception $e) {
            Log::error('登录失败：' . $e->getMessage());
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!');
        }
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $code = $this->request->post('code');
        $first = $this->request->post('first');
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($first) {
            $user->first = 1;
        }
        // $username = $this->request->post('username');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if (!$user->pid && $code) {
            $p_user = \app\common\model\User::get(['code' => $code, 'id' => ['<>', $user->id]]);
            if (isset($p_user) && !empty($p_user)) {
                $user->pid = $p_user->id;
                $pUser = \app\common\model\User::get($user->pid);
                if ($pUser) {
                    $user->paren_ids = trim($user->pid . ',' . $pUser['paren_ids'], ',');
                }
            } else {
                $this->error(__('请填写真实邀请码'));
            }
        }
        $user->save();
        $this->success();
    }



    /**
     * 绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $post = $this->request->post();
        extract($post);
        // if (!$mobile || !$captcha) {
        //     $this->error(__('Invalid parameters'));
        // }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exist'));
        }
        $result = Sms::check($mobile, $captcha, 'default');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        // if (!$user->pid) {
        //     if (isset($code)) {
        //         $p_user = \app\common\model\User::get(['code' => $code]);
        //         if ($p_user) {
        //             $pid = $p_user['id'];
        //             $pUser = \app\common\model\User::get($pid);
        //             if ($pUser) {
        //                 $paren_ids = trim($pid . ',' . $pUser['paren_ids'], ',');
        //                 $user->paren_ids = $paren_ids ?? '';
        //             }
        //         }
        //     }
        //     $user->pid = $pid ?? 0;
        // }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();
        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;
        $data = Address::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = Address::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (POST)
     */
    public function setDefaultAddress()
    {
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        Address::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (POST)
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = Address::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     */
    public function delAddress()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $data = Address::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }
    /**
     * 我的收益统计
     *
     * @ApiMethod (GET)
     */
    public function statistics()
    {
        $user = $this->auth->getUser();
        $totalMoney = bcadd($user->money, $user->no_money, 2);
        $ids = ModelUser::where("find_in_set({$user->id},paren_ids)")->column('id');
        $totalAmount = Order::whereIn('user_id', $ids)->where('status', '>', '0')->sum('pay_money');
        $peopleNum = count($ids);
        $salesVolume = $user['sales_volume'];
        $this->success('', compact('totalMoney', 'totalAmount', 'peopleNum', 'salesVolume'));
    }
    /**
     * 直推下级用户
     *
     * @ApiMethod (GET)
     */
    public function subordinate()
    {
        $uid = $this->auth->id;
        $list = ModelUser::where("pid", $uid)->paginate(10);
        $this->success('', $list);
    }
    /**
     * 用户转赠
     *
     */
    public function transfer()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($money) || empty($money)) {
            $this->error('转赠金额不能为空');
        }
        if (!isset($user_id) || empty($user_id)) {
            $this->error('用户id不能为空');
        }
        if (!isset($mobile) || empty($mobile)) {
            $this->error('用户手机号不能为空');
        }
        $userInfo = ModelUser::get($this->auth->id);
        if ($userInfo['money'] < $money) {
            $this->error('余额不足');
        }
        $user = ModelUser::get(['uuid' => $user_id, 'mobile' => $mobile]);
        if (!$user) {
            $this->error('用户不存在');
        }
        Db::startTrans();
        try {
            MoneyLog::income($user->id, $money, 2, 501, $userInfo->id);
            MoneyLog::income($userInfo->id, $money, 1, 500, $user->id);
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
        }
        $this->success('转赠成功');
    }
    /**
     * 用户申请提现
     *
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = $this->auth->getUser();
        $post['user_money'] = $user['money'];
        extract($post);
        $validate = validate('user.Withdrawal'); //使用助手函数
        if ($type == 1) {
            $scene = 'bank';
        } elseif ($type == 2) {
            $scene = 'alipay';
        } else {
            $scene = 'enterprise';
        }
        $result = $validate->scene($scene)->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        if ($user->pay_pwd != md5(md5($payPwd) . 'pcy')) {
            $this->error('支付密码不正确');
        }
        if ($user['money'] < $money) {
            $this->error('余额不足');
        }

        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        Db::startTrans();
        try {
            $post['money'] = bcmul($post['money'], 0.9, 2);
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            MoneyLog::income($user['id'], $money, 1, 502, $post['sn']);
            // $info = new Info();
            // $data = $info->get(['user_id' => $user['id']]);
            // if ($data) {
            //     $data->allowField(true)->save($post);
            // } else {
            //     $info->isUpdate(false)->allowField(true)->save($post);
            // }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * 用户提现记录
     *
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;
        if ($type == 2) {
            $withdrawal->whereTime('createtime', 'last month');
        } elseif ($type == 3) {
            if (!isset($startDate) || empty($startDate)) {
                $this->error('开始时间不能为空');
            }
            if (!isset($endDate) || empty($endDate)) {
                $this->error('结束时间不能为空');
            }
            $withdrawal->whereTime('createtime', 'between', [$startDate, $endDate]);
        } else {
            $withdrawal->whereTime('createtime', 'month');
        }
        $withdrawal->where('user_id', $this->auth->id);

        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d') as create_time")->paginate(10);
        $this->success('', $list);
    }
    /**
     * 用户余额明细
     *
     */
    public function balanceDetail()
    {
        $get = request()->get();
        extract($get);
        $moneyLog = new MoneyLog();
        if ($type == 1) {
            $moneyLog->where('type', '2');
        } else {
            $moneyLog->where('type', '1');
        }
        if ($dateType == 2) {
            $moneyLog->whereTime('createtime', 'last month');
        } elseif ($dateType == 3) {
            if (!isset($startDate) || empty($startDate)) {
                $this->error('开始时间不能为空');
            }
            if (!isset($endDate) || empty($endDate)) {
                $this->error('结束时间不能为空');
            }
            $moneyLog->whereTime('createtime', 'between', [$startDate, $endDate]);
        } else {
            $moneyLog->whereTime('createtime', 'month');
        }
        $moneyLog->where('user_id', $this->auth->id);
        $moneyLog->order('createtime desc');

        $list = $moneyLog->paginate(10);
        $this->success('', $list);
    }
    /**
     * YS互转计算
     *
     */
    public function computation()
    {
        $params = request()->param();
        extract($params);
        $commission = config('site.commission');
        $commission = array_reverse($commission, true);
        $com = 0;
        foreach ($commission as $k => $v) {
            if ($number >= $k) {
                $com = $v;
                break;
            }
        }
        if ($com > 0) {
            $num = bcdiv($com, 100, 2);
            $comm = bcmul($number, $num, 2);
        }
        $this->success('', $comm);
    }
    /**
     * YS互转
     *
     */
    public function option_swap()
    {
        $params = request()->param();
        extract($params);
        $to_user = ModelUser::get(['uuid' => $to_uid, 'mobile' => $mobile]);
        if (!$to_user) {
            $this->error('用户ID不存在');
        }
        $user = $this->auth->getUser();
        $minimum = config('site.minimum');
        $commission = config('site.commission');
        if ($number < $minimum) {
            $this->error('最低转' . $minimum . 'YS');
        }
        if ($number > $user->options) {
            $this->error('YS不足');
        }
        $commission = array_reverse($commission, true);
        $com = 0;
        foreach ($commission as $k => $v) {
            if ($number >= $k) {
                $com = $v;
                break;
            }
        }
        Db::startTrans();
        try {
            if ($com > 0) {
                $num = bcdiv($com, 100, 2);
                $comm = bcmul($number, $num, 2);
                if ($comm > $user->options) {
                    exception('YS不足');
                }
                OptionLog::income($to_user->id, $number, 2, 200, $serial);
                OptionLog::income($user->id, $number, 1, 200, $serial);
                OptionLog::income($user->id, $comm, 1, 400, $serial);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('互转失败：' . $e->getMessage());
        }
        $this->success('互转成功');
    }
    /**
     * YS兑换
     *
     */
    public function ys_exchange()
    {
        $params = request()->param();
        extract($params);
        $user = $this->auth->getUser();
        $minimum = config('site.minimum');
        if ($user->pay_pwd != md5(md5($payPwd) . 'pcy')) {
            $this->error('支付密码不正确');
        }
        if ($number < $minimum) {
            $this->error('最低兑换' . $minimum . 'YS');
        }
        if ($number > $user->options) {
            $this->error('YS不足');
        }
        Db::startTrans();
        try {
            $post['sn'] = sn('user_withdrawal', 'sn', 'DH');
            $post['user_id'] = $user['id'];
            $post['ys'] = $number;
            $tx = new Ys($post);
            $tx->allowField(true)->save();
            OptionLog::income($user->id, $number, 1, 300, $tx->sn);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('申请失败' . $e->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * 用户提现信息保存
     *
     */
    public function withdrawal_info()
    {
        $data = Info::get(['user_id' => $this->auth->id]);
        $this->success('', $data);
    }
    /**
     * 用户提现信息保存
     *
     */
    public function withdrawal_information()
    {
        $post = $this->request->post();
        $user = $this->auth->getUser();
        $info = new Info();
        $data = $info->get(['user_id' => $user['id']]);
        if ($data) {
            $res = $data->allowField(true)->save($post);
        } else {
            $post['user_id'] = $user->id;
            $res = $info->isUpdate(false)->allowField(true)->save($post);
        }
        if ($res) {
            $this->success('保存成功');
        }
        $this->error('保存失败');
    }

    /**
     * YS记录
     *
     */
    public function ys_log()
    {
        $params = request()->param();
        extract($params);
        $optionLog = new OptionLog();
        if ($dateType == 1) {
            $optionLog->whereTime('createtime', 'month');
        } elseif ($dateType == 2) {
            $optionLog->whereTime('createtime', 'last month');
        } elseif ($dateType == 3) {
            if (!$starttime || !$endtime) {
                $this->error('请选择时间范围');
            }
            $optionLog->whereTime('createtime', 'between', [$starttime, $endtime]);
        }
        $list = $optionLog->where('user_id', $this->auth->id)->where('type', $type)->paginate(10);
        $this->success('保存成功', $list);
    }

    /**
     * 积分记录
     *
     */
    public function score_log()
    {
        $params = request()->param();
        extract($params);
        $scoreLog = new ScoreLog();
        if ($dateType == 1) {
            $scoreLog->whereTime('createtime', 'month');
        } elseif ($dateType == 2) {
            $scoreLog->whereTime('createtime', 'last month');
        } elseif ($dateType == 3) {
            if (!$starttime || !$endtime) {
                $this->error('请选择时间范围');
            }
            $scoreLog->whereTime('createtime', 'between', [$starttime, $endtime]);
        }
        $list = $scoreLog->where('user_id', $this->auth->id)->where('type', $type)->paginate(10);
        $this->success('保存成功', $list);
    }
}
